package org.uned.agonzalo16.bitacora.dao;

import static org.uned.agonzalo16.bitacora.dao.OfyFactory.ofy;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Blog;
import org.uned.agonzalo16.bitacora.domain.Comment;
import org.uned.agonzalo16.bitacora.domain.User;

import com.googlecode.objectify.Key;

@Repository
public class ArticleDao {

	public List<Article> findAll() {
		return ofy().load().type(Article.class).list();
	}

	public List<Article> findByBlog(Blog blog) {
		return ofy().load().type(Article.class).filter("blog", blog).list();
	}

	public List<Article> findByUser(User user) {
		return ofy().load().type(Article.class).filter("user", user).list();
	}

	public Article get(Long id) {
		return ofy().load().type(Article.class).id(id).now();
	}

	public Article merge(Article article) {
		ofy().save().entity(article).now();
		return article;
	}

	public void delete(Long id) {
		Article article = get(id);
		List<Key<Comment>> comments = ofy().load().type(Comment.class).ancestor(article).keys().list();
		ofy().delete().type(Article.class).id(id).now();
		ofy().delete().keys(comments).now();
	}
}
